<?php defined('SYSPATH') OR die('No direct access allowed.');

class Create_Controller extends Master_Playlist_Controller 
{

	public function index()
	{
		$this->page(1);
	}

	public function page($album_id)
	{
		$view = new View('playlist/create');

		$form = array (
					'txtTitle'    => '',
					'txtDesc'    => '',
					'txtPicture' => '',
				);
		$view->form = $form;

		$playlists = new Playlists_Model;
		$view->albums = $playlists->load_albums();
		$view->songs = $playlists->load_songs($album_id);

		$this->set_title('สร้าง playlist');
		$this->template->content = $view;
		$this->template->render(TRUE);
	}


	public function ajax_page($album_id)
	{
		if(request::is_ajax())
	    {
	    	$this->auto_render=false;
	    	$ajax = new ISS_Ajax();
	    	
	    	$playlists = new Playlists_Model;
	       
			$songs = $playlists->load_songs($album_id);
		
	        $content = '	<div id="songs"><select style="width:150px"	id="cboSong"	name="cboSong">				<option value="0"></option>';
	        
			foreach ($songs as $song): 
				$content .='<option value="' .$song['album_id'].'-'.$song['track_no']. '">' .html::specialchars($song['title']) .   '</option>';
			endforeach;

			$content .='	</select></div>';

	    	

	        $selector = "songs";
			$ajax->addViewUpdate($selector, $content);
			
			echo json_encode($ajax->getHtmlAjax());
	    }
	    else {
	    	$this->page(1);
	    }
	}

	public function createplaylist()
	{
		//$_create = new Playlist_Model;
		//$result = $_create->create();

		$auth = new Auth;
		$user_id = $auth->get_user()->id;

		$playlists = new Playlists_Model;
		$playlist_name_prefix = uniqid();


		//------------------- Save Picture ------------------
		$playlists->file_validate('txtPicture',$playlist_name_prefix);
		$playlist_logo_file = str_replace(DOCROOT, '', $playlists->get_filename());
		$playlist_title = $_POST['txtTitle'];
		if (isset($_POST['txtDesc'])){
			$playlist_desc = $_POST['txtDesc'];
		}else{
			$playlist_desc = "";
		}

			if (strlen($playlist_logo_file) == 0) {
				$save_flag = 0;
			}else { 
				$save_flag = 1;
			}


	       
			
//------------------------------------------------- prepare xml string -------------------------------------------------------
//-------------- Create Header file -----------------
		$xmlHeadPlaylistSample = '<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
    <trackList>
			';

		$xmlHeadPlaylistLow = '<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
    <trackList>
			';

		$xmlHeadPlaylistHigh = '<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
    <trackList>
			';

//-------------------- Loop Create track list ----------------------

		foreach($_POST as $key => $val) // All Key & Value
		{
			$hidID = substr($key, 0,5);
			if ($hidID == "hidID"){
				$arr_val = explode("-",$val);
				$songs = $playlists->search_song($arr_val[0],$arr_val[1]); //--- array of query from model *** may be more than one record because 1 album can song more than 1 artist.
				
				//------- set variable for track playlist --------
				$song_sample = rawurlencode($songs[0]['sample_file']);
				$song_sample = str_replace('%2F','/',$song_sample);
				$song_low = rawurlencode($songs[0]['low_bit_rate_file']);
				$song_low = str_replace('%2F','/',$song_low);
				$song_high = rawurlencode($songs[0]['high_bit_rate_file']);
				$song_high = str_replace('%2F','/',$song_high);

				$album_title = $songs[0]['album_title'];
				$song_title = $songs[0]['song_title'];
				$album_cover_picture = rawurlencode($songs[0]['cover_picture']);
				$album_cover_picture = str_replace('%2F','/',$album_cover_picture);


				$artist = "";
				$artist_count = 0;
				foreach ($songs as $song):
					if ($artist_count > 0) { $artist .= " & "; }
					$artist .= $song['artist_name'];
					$artist_count ++;
				endforeach;
				
				$xmlHeadPlaylistSample .= $playlists->create_tracklist($song_sample,$artist,$album_title,$song_title,$album_cover_picture);
				$xmlHeadPlaylistLow .= $playlists->create_tracklist($song_low,$artist,$album_title,$song_title,$album_cover_picture);
				$xmlHeadPlaylistHigh .= $playlists->create_tracklist($song_high,$artist,$album_title,$song_title,$album_cover_picture);

			}
			//echo $key . " : " . $val . "<br>";
		}


//--------------- Create Footer file ----------------------
		$xmlHeadPlaylistSample .='
    </trackList>
</playlist>
		';

		$xmlHeadPlaylistLow .='
    </trackList>
</playlist>
		';

		$xmlHeadPlaylistHigh .='
    </trackList>
</playlist>
		';


//------------------------------------------------- write xml string to file -------------------------------------------------------
		
		$playlist_sample_file = $playlists->create_file_xml_playlist(1,$xmlHeadPlaylistSample,$playlist_name_prefix); // Create sample playlist
		$playlist_low_file = $playlists->create_file_xml_playlist(2,$xmlHeadPlaylistLow,$playlist_name_prefix); // Create low playlist
		$playlist_high_file = $playlists->create_file_xml_playlist(3,$xmlHeadPlaylistHigh,$playlist_name_prefix); // Create high playlist


//$playlist_title
//$playlist_desc
//$playlist_logo_file
//$playlist_sample_file
//$playlist_low_file
//$playlist_high_file
		$arr_save = array (
			'title' => $playlist_title,
			'desc' => $playlist_desc, 
			'logo' => $playlist_logo_file, 
			'sample' => $playlist_sample_file, 
			'low' => $playlist_low_file, 
			'high' => $playlist_high_file,
			'owner_id' => $user_id,
			);

					if (isset($_POST['hidMode'])){
							if ($save_flag == 0) {
								$result_edit_playlist = $playlists->save_edit($arr_save,$_POST['hidMode']);
							}elseif ($save_flag == 1){
								$result_edit_playlist = $playlists->save_edit_picture($arr_save,$_POST['hidMode']);
							}
							if ($result_edit_playlist){

								if ($playlists->playlist_song_all($_POST['hidMode'])){
											$playlist_id = $_POST['hidMode'];
											$order_no = 1;
											foreach($_POST as $key => $val) // All Key & Value
											{
												$hidID = substr($key, 0,5);
												if ($hidID == "hidID"){
													//playlist_id, album_id, track_no, order_no,
													$arr_val = explode("-",$val);
													$album_id = $arr_val[0];
													$track_no = $arr_val[1];

													$arr_playlist_song = array (
														'playlist_id' => $playlist_id,
														'album_id' => $album_id,
														'track_no' => $track_no,
														'order_no' => $order_no,
														);
													$playlists->save_playlist_song($arr_playlist_song);
													$order_no ++;
												}
											}

											url::redirect('playlist/index');
								}else { echo "update not complete - delete song on playlist error"; }
								
							}else { echo "update not complete"; }
					}else{
							if ($playlists->save($arr_save)){
								$find_playlist_id = $playlists->find_playlist_id($playlist_sample_file);
								$playlist_id = $find_playlist_id[0]['id'];

								$order_no = 1;
								foreach($_POST as $key => $val) // All Key & Value
								{
									$hidID = substr($key, 0,5);
									if ($hidID == "hidID"){
										//playlist_id, album_id, track_no, order_no,
										$arr_val = explode("-",$val);
										$album_id = $arr_val[0];
										$track_no = $arr_val[1];

										$arr_playlist_song = array (
											'playlist_id' => $playlist_id,
											'album_id' => $album_id,
											'track_no' => $track_no,
											'order_no' => $order_no,
											);
										$playlists->save_playlist_song($arr_playlist_song);
										$order_no ++;
									}
								}

								url::redirect('playlist/index');
							}else{ echo "not complete"; }
					}

	}

}
